#ifndef TCPSERVER_H
#define TCPSERVER_H

#pragma once
#include "pub.hpp"

#include "Acceptor.h"
#include "Connection.h"
#include "ThreadPool.hpp"
#include <unordered_map>
#include <vector>
#include <mutex>

class TcpServer
{
public:
    TcpServer(const std::string&, const unsigned short port, int maxEvent = 1000);
    ~TcpServer();
    void Run();
    void Stop();
private:
    uint32_t threadNums_ = 0;
    EventLoop loop_;
    std::vector<EventLoop*> subLoops_;
    // 主线程将新链接交给子线程处理
    ThreadPool* IoThreads_ = nullptr;
    // 子线程只处理IO，业务处理交给工作线程, 防止IO线程阻塞
    ThreadPool* workerThreads_ = nullptr;

    Acceptor* acceptor_ = nullptr;
    // 用一个锁保护
    std::mutex connsMtx_;
    std::unordered_map<int, ConnectionSptr> conns_;
    // 让acceptor把链接上来的socket传回来
    void acceptCb(Socket* clientSock);
    // 当有客户端链接收到消息后的回调

    // 异常退出
    void onError(ConnectionSptr conn);
    void onExit(ConnectionSptr conn);
    // 客户端收到消息时
    void onMessage(ConnectionSptr conn, const std::string);


    void workerTask(ConnectionSptr conn, const std::string& msg);
};

#endif